package io.netty.shenh.example.stickunpack;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.concurrent.DefaultEventExecutorGroup;
import io.netty.util.concurrent.EventExecutorGroup;

import java.nio.charset.Charset;
import java.util.UUID;

public class MyServerHandler extends SimpleChannelInboundHandler<ByteBuf> {

    private int count;
    /**
     * 增加处理业务线程池的一种方式, 在handler中提交任务
     */
    private static final EventExecutorGroup group = new DefaultEventExecutorGroup(8);

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, ByteBuf msg) throws Exception {
        byte[] bytes = new byte[msg.readableBytes()];
        msg.writeBytes(bytes);

        String message = new String(bytes, Charset.forName("utf-8"));
        System.out.println("服务端接收到数据: " + message);
        System.out.println("服务端接收到消息量=" + ++this.count);

        /*group.submit(() -> {
            try {
                Thread.sleep(5000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            ctx.writeAndFlush(Unpooled.copiedBuffer(UUID.randomUUID().toString(), Charset.forName("utf-8")));
        });*/

        ctx.writeAndFlush(Unpooled.copiedBuffer(UUID.randomUUID().toString(), Charset.forName("utf-8")));

    }
}
